﻿using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using DotNet.Common;

namespace CodeExchange
{
    public partial class FormCodeExchange : FormSingle
    {
        public FormCodeExchange()
        {
            InitializeComponent();
        }

        private void btnExchange_Click(object sender, EventArgs e)
        {
            string target;
            if (Exchange(textBoxSource.Text, out target))
            {
                textBoxTarget.Text = target;
                if (CommonApp.RunVerifyMessageBox(this, "转换成功，是否拷贝到系统剪切板？"))
                {
                    Clipboard.SetText(target);
                }
            }
        }

        public static bool Exchange(string source, out string target)
        {
            if (string.IsNullOrEmpty(source))
            {
                target = string.Empty;
                return false;
            }

            target = Regex.Replace(source, @"^(\s*)([^=]+)=\s*([^=;]+);", @"$1$3=$2;", RegexOptions.Multiline);

            return true;
        }

        private void FormCodeExchange_Shown(object sender, EventArgs e)
        {
            string[] cmds = Environment.GetCommandLineArgs();
            if (cmds.Length > 1)
            {
                if (Regex.IsMatch(cmds[1], @"^(\s*)([^=]+)=\s*([^=;]+);", RegexOptions.Multiline))
                {
                    textBoxSource.Text = cmds[1];
                    btnExchange_Click(null, null);
                }
            }
        }

        private void FormCodeExchange_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.Close();
            }
        }
    }
}
